package listbyorder.access001_100.test68;

import java.util.ArrayList;
import java.util.List;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/6/3 20:08
 */
public class Solution1 {

    public List<String> fullJustify(String[] words, int maxWidth) {
        List<String> ans = new ArrayList<>();   // 存储最后的结果
        List<String> row = new ArrayList<>();   // 存储每一轮遍历出来的字符串
        int curSite = 0;
        for (int i = 0; i < words.length; ) {
            if ((curSite == 0 && curSite + words[i].length() <= maxWidth) || (curSite > 0 && (curSite + 1 + words[i].length()) <= maxWidth)) {
                if (curSite == 0) {
                    curSite = curSite + words[i].length();
                } else {
                    curSite = curSite + 1 + words[i].length();
                }
                row.add(words[i]);
                i++;
            } else {
                // 首先计算出当前的空格数
                int spaceNum = maxWidth - curSite + (row.size() - 1);
                if (row.size() == 1) {
                    ans.add(row.get(0) + generateBlank(spaceNum));
                } else {
                    StringBuilder temp = new StringBuilder();
                    temp.append(row.get(0));
                    int ever = spaceNum / (row.size() - 1);
                    int more = spaceNum - ever * (row.size() - 1);
                    String moreBlank = generateBlank(ever + 1);
                    int k = 1;
                    for (int j = 0; j < more; j++) {
                        temp.append(moreBlank + row.get(k++));
                    }
                    String curBlank = generateBlank(ever);
                    for (int j = k; j < row.size(); j++) {
                        temp.append(curBlank + row.get(j));
                    }
                    ans.add(temp.toString());
                }
                // 清空row和curSite
                row.clear();
                curSite = 0;
            }
        }
        // 单独计算最后一行
        StringBuilder temp = new StringBuilder();
        temp.append(row.get(0));
        for (int j = 1; j < row.size(); j++) {
            temp.append(" " + row.get(j));
        }
        temp.append(generateBlank(maxWidth - curSite));
        ans.add(temp.toString());
        return ans;
    }

    private String generateBlank(int n) {
        StringBuilder ans = new StringBuilder();
        for (int i = 0; i < n; i++) {
            ans.append(" ");
        }
        return ans.toString();
    }

}
